const SunloginControl = require(__dirname + '/../dist/slcc-lib.js').SunloginControl;
const fs = require('fs');


// 填充参数内容以运行demo
const host = process.argv[2]; // FROM SDK: PHSRC://11840.slp2p-live01.oray.net:4118/;PHSRC_HTTPS://11840.slp2p-live01.oray.net:443/;UsingMultiChannel://; 只要主机名
const cid  = process.argv[3]; // FROM SDK: CID

var client = new SunloginControl.Client({
  // SDK
  host: host, 
  embed: true,  // SDK 传true
  ssl: false,  // node环境下可以主动忽略证书校验，即使服务器没有配置也可以运行
  cid: cid,  

  debug: true // 控制台日志输出，生产环境请关闭debug
});

var counter = 0;
var outputFd = null;

client
.autoConnect() // 客户端连接开始
.then(() => {
  // 连接桌面插件
  const desktop = new SunloginControl.Plugin.Desktop({quality: 15});
  client.connectPlugin(desktop);

  // imageinfo 桌面图像信息
  desktop.on('imageinfo', (info) => {
    // do something...
    client.on('message', (data) => {
      counter ++;
      fs.open(__dirname + '/data/' + counter + '.h264', 'w+', (err, fd) => {
        fs.write(fd, data, 0, data.byteLength, (err) => {
          fs.close(fd, (err) => {});
        });
      });
    })
  });

  client.on('disconnect', () => {
    if (outputFd) {
      fs.close(outputFd, (err) => {});
    }
  });

  // 保存视频流为文件
  // DesktopView 为通用软解方案，若客户实现解码方式监听此事件
  // stream Uint8Array H264视频流
  // info object {
  //   "streamId": 10201,
  //   "width": 1920,
  //   "height": 1080,
  //   "frameId": 0,
  //   "length": 41021,
  //   "type": 0
  // }
  fs.open(__dirname + '/stream/record.h264', 'w+', (err, fd) => {

    outputFd = fd;

    desktop.on('stream', (stream, info) => {
      // do something...
      var buf = Buffer.from(stream);

      console.log('STREAM BUFFER HEAD', buf[0], buf[1], buf[2], buf[3]);

      counter++;

      fs.write(fd, buf, 0, buf.byteLength, (err) => {
        console.log(buf.byteLength, " bytes had been write")
      });
    });
  });
})
.catch((e) => {
  console.log("Error occured: ", e);
});